<?php
namespace app\common\repositories\user;
use app\common\repositories\BaseRepository;
use app\common\dao\user\UserBalanceDao as dao;
use app\common\repositories\info\InfoRepository;
use app\common\repositories\member\MemberRecordRepository;
use app\common\repositories\member\MemberSettingRepository;
use think\exception\ValidateException;

/**
 * @mixin dao
 */
class UserBalanceRepository extends BaseRepository
{
    public function __construct(dao $dao)
    {
        $this->dao = $dao;
    }

    public function getApiList($where,$page,$limit)
    {
        $count = $this->dao->getSearch()->where($where)->count();
        $list = $this->dao->getSearch()->where($where)->order('record_id desc')->page($page,$limit)->select();
        return compact('count','list');
    }


    public function dealSpreadBrokerage($spreadUid,$id,$type = 'info')
    {
        if(!$spreadUid) return;

        /**@var $make MemberSettingRepository**/
        $make = app()->make(MemberSettingRepository::class);
        $memberType = $make->getUserMemberType($spreadUid);
        if($memberType == 0){
            return;
        }

        $orderMake = $type == 'info' ? app()->make(InfoRepository::class) : app()->make(MemberRecordRepository::class);

        $order = $orderMake->get($id);
        if(!$order) return;
        if($type == 'info' && in_array($order->type,['0','7'])){
            return;
        }

        $rate = systemConfig('member_brokerage_percent') ?: 0;
        $brokerage = bcmul($rate,$order->price,2);
        if($brokerage <= 0) return;

        $this->recordBalance($spreadUid,1,'brokerage','分销佣金',$brokerage);

        if($type == 'info'){
            $order->save(['brokerage'=>$brokerage,'spread_uid'=>$spreadUid]);
        }
    }

    public function recordBalance($uid,$type,$cate,$desc,$price)
    {
        $this->userBalance($uid,($type ? 1 : -1)*$price);
        $this->record(...func_get_args());
    }


    public function record($uid,$type,$cate,$desc,$price)
    {
        $this->dao->create(compact('uid','type','cate','desc','price'));
    }


    public function userBalance($uid,$balance)
    {
        app()->make(UserRepository::class)->incrNumberField($uid,'balance',$balance);
    }


}